package com.zxcz.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.iot.model.v20180120.QueryProductResponse;
import com.aliyuncs.iot.model.v20180120.QueryProductResponse.Data;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxcz.aliyun.IotConfig;
import com.zxcz.aliyun.IotManager;
import com.zxcz.domain.IotProduct;
import com.zxcz.domain.Result;
import com.zxcz.mapper.IotProductMapper;
import com.zxcz.service.IotProductService;
import com.zxcz.tools.CustomHttpStatus;
import com.zxcz.tools.ResultUtil;

@Service
public class IotProductServiceImpl implements IotProductService{
	@Autowired
	private IotProductMapper iotProductMapper;
	@Autowired
	private IotConfig iotConfig;
	@Autowired
	private IotManager iotManager;

	@Override
	public Result<Object> queryIotProduct() {
		List<IotProduct> iotProducts = iotProductMapper.queryIotProduct();
		HashMap<String,Object> map = new HashMap<>();
		map.put("iotProducts", iotProducts);
		return new ResultUtil().generate(CustomHttpStatus.SUCCESS, map);
	}

	private IotProduct selectIotProductByKey(String productKey) {
		return iotProductMapper.selectIotProductByKey(productKey);
	}

	@Override
	public Result<Object> importProducts() {
		List<IotProduct> iotList = new ArrayList<>();
		//取出配置文件的productKey
		List<String> productKeyList = iotConfig.getDeviceProductKey();
		
		for(String productKey : productKeyList) {
			//查询数据库是否已经存在该产品
			IotProduct product = this.selectIotProductByKey(productKey);
			
			//当数据库不存在该产品则导入
			if(product == null) {
				//获取物联网平台上该产品的信息
				QueryProductResponse response = iotManager.QueryProduct(productKey);
				Data data = response.getData();
				IotProduct iotProduct = new IotProduct();
				iotProduct.setProductKey(data.getProductKey());
				iotProduct.setProductName(data.getProductName());
				iotProduct.setProductSecret(data.getProductSecret());
				iotProduct.setCreatedAt(new Date());
				iotProduct.setUpdatedAt(new Date());
				
				//添加到数据库
				iotProductMapper.insertIotProduct(iotProduct);
				iotList.add(iotProduct);
			}
		}
		
		HashMap<String,Object> map = new HashMap<>();
		map.put("iotProducts", iotList);
		return new ResultUtil().generate(CustomHttpStatus.SUCCESS, map);
	}

}
